/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */
#include "TCPClientServer.h"

void SuperClient::run()
{
	TCPClientThreadBuffer::run();
	TCPClientServer::serverInstance()->Terminate();
}

TCPClientServer * TCPClientServer::instance = NULL;

bool TCPClientServer::init()
{
	if ( !this->connect("127.0.0.1", 8888) )
	{
		return false;
	}

	while ( !superClient.verified )
	{
		unsigned char cmd[SocketConnection::MAX_DATASIZE];
		int nBytes = superClient.recvPacket(cmd, true);//一定要取一个包
		if ( nBytes < 0 )
			return false;
		else if ( nBytes > 0 )
		{
			superClient.msgParse(cmd, nBytes);
		}
	}
	debug("success login");

	return superClient.start();
}

bool TCPClientServer::connect(const char * serverip, const unsigned short port)
{
	if ( !superClient.connect(serverip, port ) )
	{
		debug("can not connect port %d", superClient.serverPort);
		return false;
	}

	debug("success connect port %d", superClient.serverPort);

	//send request start up cmd;superclient->sendcmd;
	while ( !sendLoginCmd() ) // must send the request login packet
		;
	return true;
}

TCPClientServer::~TCPClientServer()
{
	instance = NULL;
}

void TCPClientServer::recycle()
{
	superClient.stop();
	superClient.join();
	TCPServer::recycle();
	//superClient.~TCPClientThread();//forcesync, delete pSocket;
}

